﻿using Microsoft.AspNetCore.Server.Kestrel.Core;
using System.Net;
using NLog.Web;

namespace ScienceRpcServe;

public static class HrImageServeConfigure
{
    private static int port;
    private static string ip;
    private static int transSize;
    private static string settings = "GrpcSettings";

    public static void Setting(this WebApplicationBuilder builder)
    {
        ip = builder.Configuration.GetSection(settings).GetSection("IpAddress").Value;
        port = Convert.ToInt32(builder.Configuration.GetSection(settings).GetSection("Port").Value);
        transSize = Convert.ToInt32(builder.Configuration.GetSection(settings).GetSection("TransSize").Value);
    }

    public static void ConfigureNLog(this WebApplicationBuilder builder)
    {
        NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");
        builder.Logging.ClearProviders();
        builder.Host.UseNLog();
    }

    public static void ConfigureKestrel(this WebApplicationBuilder builder)
    {
        builder.WebHost.ConfigureKestrel(options =>
        {
            options.Listen(new IPEndPoint(IPAddress.Parse(ip), port), listenOptions =>
            {
                listenOptions.Protocols = HttpProtocols.Http2;
                listenOptions.KestrelServerOptions.Limits.Http2.MaxFrameSize = transSize;
            });
        });
    }

    /// <summary>
    /// todo 后续补全
    /// </summary>
    /// <param name="builder"></param>
    public static void ConfigureMqttSubscribe(this WebApplicationBuilder builder)
    {
        //new Thread(async () =>
        //{
        //    var mqttSetting = builder.Configuration.GetSection("MqttSetting");
        //    HrImageServerMqttUtil.Instance.InitialParams(mqttSetting);
        //    await HrImageServerMqttUtil.Instance.SubScribeMqttAsync();

        //    // 心跳检测开启
        //    HrImageServerMqttUtil.Instance.HeartBeat();
        //}).Start();
    }

    public static string ConfigureDbSetting(this WebApplicationBuilder builder)
    {
        var path = builder.Configuration.GetSection("DatabaseSetting").GetSection("DbDirPath").Value;
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        return path;
    }

}

